package com.techsoul.module.system.service.impl;

import com.techsoul.common.core.exception.BusinessException;
import com.techsoul.common.core.util.file.FileUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.module.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.Iterator;

@Slf4j
@Service
@Transactional(readOnly = true)
public class FileServiceImpl implements IFileService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private IConfigService configService;

    /**
     * 上传附件
     * @param request
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String upload(MultipartHttpServletRequest request) {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String descFilename = null;
        try {
            // 判断文件是否存在
            if (request.getMultiFileMap() != null) {
                Iterator<String> fileNames = request.getFileNames(); // 取得request中的所有文件名
                while (fileNames.hasNext()) {
                    // 源文件
                    MultipartFile originalFile = request.getFile(fileNames.next());
                    if (originalFile != null) {
                        // 源文件名称
                        String originalFilename = originalFile.getOriginalFilename();
                        if (StringUtils.isNotBlank(originalFilename)) {
                            // 源文件扩展名
                            String fileExtension = FileUtils.getFileExtension(originalFilename);
                            // 目标文件名
                            descFilename = idWorker.nextId() + "." + fileExtension;
                            File descFile = new File(baseDir + descFilename);
                            // 如果目标文件所在的目录不存在，则创建目录
                            if (!descFile.getParentFile().exists()) {
                                descFile.getParentFile().mkdirs();
                            }
                            // 保存文件到指定路径
                            originalFile.transferTo(descFile);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(e);
        }
        return descFilename;
    }

}
